package org.springblade.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2025-08-12 10:11
 */
@Configuration
public class BaseConfig {


	/**
	 * 返回限流KEY
	 * @return
	 */
	@Bean
	KeyResolver userKeyResolver() {
		// 按用户限流
		return exchange -> {
			return Mono.just(exchange.getRequest().getQueryParams().getFirst("id"));
			// 按IP限流
			// return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
		};
	}

    @Bean
    public RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(10, 20);
    }
	// 自定义过滤器 Bean
	@Bean
	public CustomGatewayFilter customGatewayFilter() {
		return new CustomGatewayFilter();
	}
    // 手动路由 - 高优先级
    @Bean
    @Order(-1)
    public RouteLocator customRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("custom-route", r -> r
                .path("/ctms-provider/special/**")
                .filters(f -> f
                    // 添加限流过滤器
                    .requestRateLimiter(c -> {
                        c.setRateLimiter(redisRateLimiter());
                        c.setKeyResolver(userKeyResolver());
                    })
                    // 添加自定义过滤器
                    .filter(customGatewayFilter())
                    // 添加其他过滤器
                    .addRequestHeader("X-Route-Name", "custom-route")
                    .rewritePath("/ctms-provider/special/(?<segment>.*)", "/special/${segment}")
                )
                .uri("lb://ctms-provider"))
            .build();
    }
}
